package com.ia.admin.article;

import com.ia.cache.CatalogCache;
import com.ia.util.ShowMessage;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;

/**
 * Created by ipc on 15/10/26.
 */
public class ArticleController extends Controller {

    public void index() {
        int cid = getParaToInt("cid", -1);
        String title = getPara("title", "");

        int fromPage = getParaToInt("from", 1);
        Page<Article> articlePage = Article.me.search(fromPage, 10, cid, title);
        setAttr("articlePage", articlePage);

        setAttr("cid", cid);
        setAttr("title", title);
        setAttr("urlParas", "?cid=" + cid + "&title=" + title);
        setAttr("catalogCache", CatalogCache.getInstance());

        render("index.html");
    }

    public void add() {
        setAttr("catalogCache", CatalogCache.getInstance());
        render("add.html");
    }

    public void save() {
        Article article = getModel(Article.class);
        article.set("create_time", new Date());
        article.save();

        setAttr("showMessage", ShowMessage.ADD_SUCCESS);

        index();
    }

    public void edit() {
        setAttr("article", Article.me.findById(getPara("id")));
        setAttr("catalogCache", CatalogCache.getInstance());

        render("edit.html");
    }

    public void update() {
        getModel(Article.class).update();
        setAttr("showMessage", ShowMessage.UPDATE_SUCCESS);

        index();
    }

    public void delete() {
        Article.me.deleteById(getPara("id"));
        setAttr("showMessage", ShowMessage.DELETE_SUCCESS);

        index();
    }

    public void view() {
        setAttr("article", Article.me.findById(getPara("id")));
        setAttr("catalogCache", CatalogCache.getInstance());
        render("view.html");
    }

}
